package com.yuyou.hxyy.gateway.security.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.hxyy.service.api.bean.LoginRedisObj;
import com.yuyou.hxyy.service.api.bean.ReturnCode;
import com.yuyou.hxyy.service.api.bean.ReturnResult;
import com.yuyou.hxyy.service.api.cons.CommCons;
import com.yuyou.hxyy.service.api.util.SpringUtil;

public class VerifyTokenFilter extends OncePerRequestFilter {

	private StringRedisTemplate stringRedisTemplate;
	
	private static  List<String> exclusiveList=new ArrayList<String>();
	
	static {		
		exclusiveList.add("login");
		exclusiveList.add("api-docs");
		exclusiveList.add("Captcha");
		exclusiveList.add("swagger");
		exclusiveList.add("health");
		exclusiveList.add("getAudio");
	}
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		Environment env=(Environment)SpringUtil.getBean("environment");
		boolean swagger=Boolean.valueOf(env.getProperty("enable.swagger"));
		boolean on=Boolean.valueOf(env.getProperty("enable.on"));
		
		if(on){
			filterChain.doFilter(request,response);
			return;
		}
		String uri=request.getRequestURI();
		//登录绕过拦截器
		if(!swagger && uri.contains("swagger")){
			return;
		}
		for(String exUri:exclusiveList){
			if(uri.contains(exUri)){
			filterChain.doFilter(request,response);
	        return;
			}
		}
		
		stringRedisTemplate=(StringRedisTemplate)SpringUtil.getBean("stringRedisTemplate");		
		String accessToken=request.getHeader("accessToken");	
        if(StringUtils.isEmpty(accessToken)){
        	accessToken = request.getParameter("accessToken") ;
        }
		if(StringUtils.isEmpty(accessToken)){
			out(response);
			return;
		}
		
		String jsonObj=stringRedisTemplate.opsForValue().get(accessToken);
		if(StringUtils.isEmpty(jsonObj)){
			out(response);
			return;
		}
		LoginRedisObj obj=JSONObject.parseObject(jsonObj, new TypeReference<LoginRedisObj>() {});	
		
		//每次请求把改用户对象放进上下文以作权限等判断
		Authentication authentication = new AcessTokenAuthentication(obj, true);		
	    SecurityContextHolder.getContext().setAuthentication(authentication);
	    	    
		//延长时间
		stringRedisTemplate.expire(accessToken, CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);     
		stringRedisTemplate.expire(String.valueOf(obj.getUserId()), CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);
	    filterChain.doFilter(request,response);
		
	}
	
	private void out(HttpServletResponse response) throws IOException {	
		ReturnResult<String> resp=new ReturnResult<String>(false,ReturnCode.code._3001.getMessage(),null,ReturnCode.code._3001.getCode(),ReturnCode.code._3001.getMessage());
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String data = resp.toJsonString();
		PrintWriter pw = response.getWriter();
		pw.write(data);
	}
	
	
}
